package com.qunar.maomao.escape;

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Escapes {
	
	private static Pattern utf_16_pat = Pattern.compile("\\\\[uU]([a-fA-F0-9]{4})");
	
	public static String transiformUTF_16( String str ) throws MalformedEscapeException{
		StringBuffer buffer = new StringBuffer( str.length() );
		Matcher mat = utf_16_pat.matcher(str);
		int start = 0;
		while( mat.find() ){
			int matched_start = mat.start();
			if( start != matched_start )
				buffer.append( str, start, matched_start );
			int off = mat.start(1);
			buffer.append( charFromUTF_16(str.charAt(off),str.charAt(off+1),
					str.charAt(off+2),str.charAt(off+3)));
			start = mat.end();
		}
		buffer.append( str, start, str.length() );
		return buffer.toString();
	}
	
	private static char charFromUTF_16( char c1, char c2, char c3, char c4 ) throws MalformedEscapeException{
		byte high = byteFromUTF_16(c1, c2);
		byte low = byteFromUTF_16(c3, c4);
		int reuslt = ( high << 8 ) + ( low & 0xFF );
		return (char)reuslt;
	}
	
	private static byte byteFromUTF_16( char c1, char c2 ) throws MalformedEscapeException{
		int high = Character.digit( c1, 16 );
		int low = Character.digit( c2, 16 );
		if( high == -1 || low == -1 )
			throw new MalformedEscapeException(String.format("MalformedEscapeException:%c %c",c1,c2));
		int result = ( high << 4 ) + low;
		return (byte)result;
	}
}
